package network;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.Socket;

public class FileDownLoadClientThread extends Thread {
	Socket socket;
	SocketData sd;
	byte[] data = new byte[10240];
	String saveFolder="/downloadclient/";
	String ip;
	int    port;

	public FileDownLoadClientThread(SocketData sd) {
		this.sd = sd;
		String[] temp = ((String)sd.getObj()).split(",");
		ip = temp[0];
		port = Integer.parseInt(temp[1]);
		
		saveFolder += port + "/";
		File f = new File(saveFolder);
		if(! f.exists()) f.mkdirs();
	}

	@Override
	public void run() {
		try {
			socket = new Socket(ip, port);
			String temp = (String) sd.getObj();
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			
			String temp2 = dis.readUTF();
			int pos = temp2.lastIndexOf("\\");
			System.out.println("temp2 = " + temp2);
			String fileName = temp2.substring(pos+1);
			
			String f = saveFolder + fileName;
			FileOutputStream fos = new FileOutputStream(f);
			
			
			int len = 0;
			int cnt = 0;
			long tempLen = 0l;

			while (true) {
				len = dis.read(data, 0, data.length);
				if (len == -1)
					break;
				fos.write(data, 0, len);
				tempLen += len;
				System.out.println(cnt + "," + len);
				cnt++;

			}
			fos.close();
			dis.close();
			socket.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
